﻿#if UNITY_EDITOR

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace AI.Graph.Editor {


    [CustomEditor (typeof (FieldOfView))]
    public class FieldOfViewInspector : UnityEditor.Editor {

        private bool drawHandles;


        public override void OnInspectorGUI () {
            base.OnInspectorGUI ();

            drawHandles = EditorGUILayout.Toggle ("Draw Handles", drawHandles);
        }


        void OnSceneGUI () {
            FieldOfView fov = target as FieldOfView;
            if (fov && drawHandles) {
                DrawFieldOfView (fov.transform, fov.viewRadius, fov.viewAngle, fov.visibleTargets);
            }
        }


        public static void DrawFieldOfView (Transform transform, float viewRadius, float viewAngle, List<GameObject> visibleTargets) {
            Vector3 position = transform.position;
            
            Handles.color = Color.white;
            Handles.DrawWireArc (position, Vector3.up, Vector3.forward, 360, viewRadius);
            Vector3 viewAngleA = DirectionFromAngle (transform, -viewAngle / 2);
            Vector3 viewAngleB = DirectionFromAngle (transform, viewAngle / 2);

            Handles.color = new Color32 (70, 230, 25, 30);
            Handles.DrawSolidArc (position, Vector3.up, viewAngleA, viewAngle, viewRadius);

            Handles.color = Color.white;
            Handles.DrawLine (position, position + viewAngleA * viewRadius);
            Handles.DrawLine (position, position + viewAngleB * viewRadius);

            Handles.color = Color.red;
            foreach (GameObject visibleTarget in visibleTargets) {
                Handles.DrawLine (position, visibleTarget.transform.position);
            }
        }


        public static Vector3 DirectionFromAngle (Transform transform, float angleInDegrees) {
            return new Vector3 (Mathf.Sin ((angleInDegrees + transform.eulerAngles.y) * Mathf.Deg2Rad), 0, Mathf.Cos ((angleInDegrees + transform.eulerAngles.y) * Mathf.Deg2Rad));
        }

    }


}
#endif